<?php
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;


if(! function_exists('qiniu_token')){
    /**
     * @return array
     * @throws Exception
     * 删除文件
     *
     */
    function qiniu_token($bucket)
    {
        $auth = new Auth(config('upload.accessKey'),config('upload.secretKey'));
        $token = $auth->uploadToken($bucket);
        $source_prefix = $bucket=='factsource'?'source1':$bucket=='reportsource'?'source2':'source3';
        $file_name = date('Ymd',time())."/".$source_prefix.substr(md5(time().mt_rand(100,999)),0,20);
        if($token){
            return ['status_code'=>HTTP_SUCCESS,'data'=>['key'=>$file_name,'token'=>$token]];
        }else{
            return ['status_code'=>SYSTEM_ERROR,'msg'=>'get token happen error'];
        }
    }
}

if (! function_exists('qiniu_upload')) {

    /**
     * @param $file_path  本地文件绝对地址文件名
     * @param $file_extension  文件后缀
     * @param $bucket  空间名
     * @return \Laravel\Lumen\Http\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * @throws Exception
     */
    function qiniu_upload($file_path, $file_extension,$bucket)
    {
        $auth = new Auth(config('upload.accessKey'),config('upload.secretKey'));
        $token = $auth->uploadToken($bucket);
        $uploadMgr = new UploadManager();
        $source_prefix = $bucket=='factsource'?'source1':$bucket=='reportsource'?'source2':'source3';
        $file_name = date('Ymd').'/'.$source_prefix.substr(md5(time().rand(100,999)),0,10).".".$file_extension;
        list($ret, $err) = $uploadMgr->putFile($token, $file_name, $file_path);
        if(is_null($err)){
            return ['status'=>HTTP_SUCCESS,'data'=>$ret];
        }else{
            return ['status'=>SYSTEM_ERROR,'msg'=>$err];
        }
    }

}




if(! function_exists('qiniu_delete')){
    /**
     * @param $bucket  仓库名
     * @param $file_name   文件目录和文件名
     * @return array
     * @throws Exception
     * 删除文件
     *
     */
    function qiniu_delete($bucket,$file_name)
    {
        $auth = new Auth(config('upload.accessKey'),config('upload.secretKey'));
        $bucketMgr = new BucketManager($auth);
        $err = $bucketMgr->delete($bucket, $file_name);
        if($err !== null){
            return ['status'=>'error'];
        }else{
            return ['status'=>'success'];
        }
    }
}

if(! function_exists('qiniu_copy')){

    /**
     * @param $key1 源key
     * @param $key2 新key
     * @param $bucket1 源仓库
     * @param $bucket2 新仓库
     * 七牛移动文件
     */
    function qiniu_copy($key1,$key2,$bucket1='reportsource',$bucket2='factsource'){
        $auth = new Auth(config('upload.accessKey'),config('upload.secretKey'));
        $bucketMgr = new BucketManager($auth);
        $bucketMgr->copy($bucket1, $key1, $bucket2, $key2);
    }
}


if(! function_exists('qiniu_fops')){
    /**
     * 七牛视频编码格式转换
     */
    function qiniu_fops($file_url,$prefix='http://reportsource.jtpk668.com/'){
        $auth = new \Qiniu\Auth(config('upload.accessKey'),config('upload.secretKey'));
        //要转码的文件所在的空间和文件名。
        $bucket = config('upload.bucket_report');
        //转码是使用的队列名称。 https://portal.qiniu.com/mps/pipeline
        $pipeline = config('upload.video_format_pipeline');
        $pfop = new \Qiniu\Processing\PersistentFop($auth, $bucket, $pipeline);
        $key = str_replace($prefix,'',strstr($file_url,'.MOV',true));
        $string = base64_encode($bucket.":".$key.'.mp4');
        //要进行转码的转码操作。 http://developer.qiniu.com/docs/v6/api/reference/fop/av/avthumb.html
        $fops = config('upload.video_format_info').$string;
        $result = $pfop->execute(str_replace($prefix,'',$file_url), $fops);
        return $result;
    }
}







if(! function_exists('insert_three_detail_extend')){

    /**
     * 阿里第三方用户详情 json
     */
    function redis_get_three_detail_extend($three_id,$type='alipay'){
        $redis = new \Redis();
        $redis->connect('115.159.216.187',6379);
        $redis->auth('api_jtpk668_com');
        $result = $redis->get(md5($three_id));
        $redis->close();
        return $result;
    }
}

if(! function_exists('emoji_content_encode')){
    /**
     * emjon 编码
     */
    function emoji_content_encode($str){
        if(!is_string($str))return $str;
        if(!$str || $str=='undefined')return '';
        $text = json_encode($str); //暴露出unicode
        $text = preg_replace_callback("/(\\\u[ed][0-9a-f]{3})/i",function($str){
            return addslashes($str[0]);
        },$text); //将emoji的unicode留下，其他不动，这里的正则比原答案增加了d，因为我发现我很多emoji实际上是\ud开头的，反而暂时没发现有\ue开头。
        return json_decode($text);
    }
}

if(! function_exists('emoji_content_decode')){
    /**
     * emjon 编码
     */
    function emoji_content_decode($str){
        $text = json_encode($str); //暴露出unicode
        $text = preg_replace_callback('/\\\\\\\\/i',function($str){
            return '\\';
        },$text); //将两条斜杠变成一条，其他不动
        return json_decode($text);
    }
}





/**
 * des 加密
 */
if(! function_exists('des_encrypt')){
    function des_encrypt($input, $key) {
        $size = mcrypt_get_block_size(MCRYPT_DES, MCRYPT_MODE_ECB);
        $input = pkcs5_pad($input, $size);
        $td = mcrypt_module_open(MCRYPT_DES, '', MCRYPT_MODE_ECB, '');
        $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td));
        mcrypt_generic_init($td, $key, $iv);
        $data = mcrypt_generic($td, $input);
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        $data = bin2hex($data);
        return $data;
    }
}


/**
 * des 解密
 */
if(! function_exists('des_decrypt')){
    function des_decrypt($sStr, $sKey) {
        $decrypted= mcrypt_decrypt(
            MCRYPT_DES,
            $sKey,
            pack("H*",$sStr),
            MCRYPT_MODE_ECB
        );
        $dec_s = strlen($decrypted);
        $padding = ord($decrypted[$dec_s-1]);
        $decrypted = substr($decrypted, 0, -$padding);
        return $decrypted;
    }
}


/**
 * 举报数据添加前缀
 */
if(! function_exists('append_thumbnail')){
    function append_thumbnail ($value) {
        return $value.env('APP_SOURCE_LIST_THUMBNAIL');
    }
}


/**
 *
 */
if(! function_exists('pkcs5_pad')){
    function pkcs5_pad ($text, $blocksize) {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }
}


if(! function_exists('validateIDCard')){
    function validateIDCard($IDCard) {
        if (strlen($IDCard) == 18) {
            return check18IDCard($IDCard);
        } elseif ((strlen($IDCard) == 15)) {
            $IDCard = convertIDCard15to18($IDCard);
            return check18IDCard($IDCard);
        } else {
            return false;
        }
    }
}

/**
 * 计算身份证的最后一位验证码,根据国家标准GB 11643-1999
 */
if(! function_exists('calcIDCardCode')){
    function calcIDCardCode($IDCardBody) {
        if (strlen($IDCardBody) != 17) {
            return false;
        }
        //加权因子
        $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
        //校验码对应值
        $code = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
        $checksum = 0;
        for ($i = 0; $i < strlen($IDCardBody); $i++) {
            $checksum += substr($IDCardBody, $i, 1) * $factor[$i];
        }
        return $code[$checksum % 11];
    }
}


/**
 * 将15位身份证升级到18位
 */
if(! function_exists('convertIDCard15to18')){
    function convertIDCard15to18($IDCard) {
        if (strlen($IDCard) != 15) {
            return false;
        } else {
            // 如果身份证顺序码是996 997 998 999，这些是为百岁以上老人的特殊编码
            if (array_search(substr($IDCard, 12, 3), array('996', '997', '998', '999')) !== false) {
                $IDCard = substr($IDCard, 0, 6) . '18' . substr($IDCard, 6, 9);
            } else {
                $IDCard = substr($IDCard, 0, 6) . '19' . substr($IDCard, 6, 9);
            }
        }
        $IDCard = $IDCard . calcIDCardCode($IDCard);
        return $IDCard;
    }
}



/**
 * 18位身份证校验码有效性检查
 */
if(! function_exists('check18IDCard')){
    function check18IDCard($IDCard) {
        if (strlen($IDCard) != 18) {
            return false;
        }
        $IDCardBody = substr($IDCard, 0, 17); //身份证主体
        $IDCardCode = strtoupper(substr($IDCard, 17, 1)); //身份证最后一位的验证码

        if (calcIDCardCode($IDCardBody) != $IDCardCode) {
            return false;
        } else {
            return true;
        }
    }
}

if(! function_exists('police_request_by_curl')){
    function police_request_by_curl($remote_server, $post_string) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $remote_server);
        curl_setopt($ch, CURLOPT_POSTFIELDS, 'params=' . $post_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERAGENT, "qianyunlai.com's CURL Example beta");
        $data = curl_exec($ch);
        curl_close($ch);

        return $data;
    }
}
/**
 * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
 * @param $para 需要拼接的数组
 * return 拼接完成以后的字符串
 */
 if(! function_exists('createLinkstring')){
	function createLinkstring($para) {
		//sort($para);
		$arg  = "";
		while (list ($key, $val) = each ($para)) {
			$arg.=$key."=".$val."&";
		}
		//去掉最后一个&字符
		$arg = substr($arg,0,count($arg)-2);
		
		//如果存在转义字符，那么去掉转义
		if(get_magic_quotes_gpc()){$arg = stripslashes($arg);}
		
		return $arg;
	}
}
/**
 * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
 * @param $para 需要拼接的数组
 * return 拼接完成以后的字符串
 */
 if(! function_exists('createLinkstringByforeach')){
	function createLinkstringByforeach($para) {
		//sort($para);
		$arg  = "";
		foreach($para as $key=>$value){
			$arg.=$key."=".$value."&";
		}
		//去掉最后一个&字符
		$arg = substr($arg,0,count($arg)-2);
		
		//如果存在转义字符，那么去掉转义
		if(get_magic_quotes_gpc()){$arg = stripslashes($arg);}
		
		return $arg;
	}
}
/**
 * RSA签名
 * @param $data 待签名数据
 * @param $private_key 商户私钥字符串
 * return 签名结果
 */
 if(! function_exists('rsaSign')){
	function rsaSign($data, $private_key) {
		//以下为了初始化私钥，保证在您填写私钥时不管是带格式还是不带格式都可以通过验证。
		$private_key=str_replace("-----BEGIN RSA PRIVATE KEY-----","",$private_key);
		$private_key=str_replace("-----END RSA PRIVATE KEY-----","",$private_key);
		$private_key=str_replace("\n","",$private_key);

		$private_key="-----BEGIN RSA PRIVATE KEY-----".PHP_EOL .wordwrap($private_key, 64, "\n", true). PHP_EOL."-----END RSA PRIVATE KEY-----";

		$res=openssl_get_privatekey($private_key);

		if($res)
		{
			openssl_sign($data, $sign,$res);
		}
		else {
			echo "fail";
			exit();
		}
		openssl_free_key($res);
		//base64编码
		$sign = base64_encode($sign);
		return $sign;
	}
}
/**
 * RSA验签
 * @param $data 待签名数据
 * @param $alipay_public_key 支付宝的公钥字符串
 * @param $sign 要校对的的签名结果
 * return 验证结果
 */
 if(! function_exists('rsaVerify')){
	function rsaVerify($data, $public_key, $sign)  {
		//以下为了初始化私钥，保证在您填写私钥时不管是带格式还是不带格式都可以通过验证。
		$public_key=str_replace("-----BEGIN PUBLIC KEY-----","",$public_key);
		$public_key=str_replace("-----END PUBLIC KEY-----","",$public_key);
		$public_key=str_replace("\n","",$public_key);

		$public_key='-----BEGIN PUBLIC KEY-----'.PHP_EOL.wordwrap($public_key, 64, "\n", true) .PHP_EOL.'-----END PUBLIC KEY-----';
		$res=openssl_get_publickey($public_key);
		if($res)
		{
			$result = (bool)openssl_verify($data, base64_decode($sign), $res);
		}
		else {
			$result ="您的公钥格式不正确!"."<br/>"."The format of your alipay_public_key is incorrect!";
		}
		openssl_free_key($res);    
		return $result;
	}
}
/**
 * 把数组所有元素，按照$header+$value+$footer”字符拼接成字符串
 * @param $para 需要拼接的数组
 * @param $header 需要拼接前部
 * @param $footer 需要拼接尾部
 * return 拼接完成以后的字符串
 */
 if(! function_exists('createPathstring')){
	function createPathstring($para,$header,$footer) {
		if(empty($para)) return "";
		//sort($para);
		$arg  = "";
		while (list ($key, $val) = each ($para)) {
			$arg.=$header.$val.$footer;
		}
		//去掉最后一个&字符
		if(strlen($arg)>1) $arg = substr($arg,0,count($arg)-2);
		
		//如果存在转义字符，那么去掉转义
		// if(get_magic_quotes_gpc()){$arg = stripslashes($arg);}
		
		return $arg;
	}
}
// http请求
/**
 * http请求
 * @param $method 请求方式
 * @param $url 请求url
 * @param $header 请求头部信息$headr[] 
 * @param $footer 请求参数
 * return 拼接完成以后的字符串
 */
 if(! function_exists('curlinfo_header')){
    function curlinfo_header($method,$url,$headr,$data,$timeout=120){
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
	  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	  curl_setopt($ch, CURLOPT_HTTPHEADER,$headr);
      curl_setopt($ch, CURLOPT_HEADER, 0); // 不要http header 加快效率
      curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
      curl_setopt($ch, CURLOPT_TIMEOUT,$timeout);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);    // https请求 不验证证书和hosts
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	  curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
      $output = curl_exec($ch);
      curl_close($ch);
      return $output;
    }
 }
 //举报发奖签名
if(! function_exists('report_sign')){
    function report_sign($info){
    	$key='W9sYsM8BUm2T8Uxb9x1oiHJJr5MgDyk3';
    	//return ($info['alipay_uid'].sprintf("%.2f",$info['amount']).$info['reportid'].$info['creat_time'].$key);
    	return md5(($info['alipay_uid'].sprintf("%.2f",$info['amount']).$info['reportid'].$info['creat_time'].$key),false);
    }
}
